﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sunboxsoft.Bases.Web.Services
{
    public class QueryService
    {
        static List<Models.Menu> s_menus = null;
        static List<Models.Role> s_roles = null;
        public List<Models.Menu> QueryMenus()
        {
            string roleId = CookieUtility.GetRoleId();
            if (string.IsNullOrEmpty(roleId))
            {
                return new List<Models.Menu>();
            }

            if (s_menus == null)
            {
                try
                {
                    string filePath = System.Web.HttpContext.Current.Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["Bases.MenuConfigFile"]);
                    s_menus = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Models.Menu>>(System.IO.File.ReadAllText(filePath));
                }
                catch (Exception ex)
                {
                    return new List<Models.Menu>();
                }
            }

            List<Models.Role> roles = QueryRoles();
            Models.Role role = roles.FirstOrDefault(p => p.Code == roleId);
            if (role == null)
            {
                return new List<Models.Menu>();
            }


            return ResovleMenus(s_menus, role);
        }

        private List<Models.Menu> ResovleMenus(List<Models.Menu> menus, Models.Role role)
        {
            List<Models.Menu> list = new List<Models.Menu>();
            for (int index = 0; index < menus.Count; index++)
            {
                if (role.Resources.Contains(menus[index].ResourceCode))
                {
                    Models.Menu menu = menus[index].Clone() as Models.Menu;
                    list.Add(menu);
                    if (menus[index].Children != null)
                    {
                        menu.Children = ResovleMenus(menus[index].Children, role);
                    }
                }
            }
            return list;
        }

        public List<Models.Role> QueryRoles()
        {
            if (s_roles == null)
            {
                try
                {
                    string filePath = System.Web.HttpContext.Current.Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["Bases.RoleConfigFile"]);
                    s_roles = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Models.Role>>(System.IO.File.ReadAllText(filePath));
                }
                catch (Exception ex)
                {
                    return new List<Models.Role>();
                }
            }

            return s_roles;
        }
    }
}
